package com.ustcinfo.study.hive.r1.cuiyang;

import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 统计出各域名访问个数
 * Author: cuiyang
 * Date: 2018-08-03-19:22
 */
public class HiveConnection {
    // hive链接地址
    private static String url = "jdbc:hive2://nodex:10000/default";

    //root用户名
    private static String userName = "root";

    // root密码
    private static String passwd = "000000";

    // hive 驱动
    private static String driver = "org.apache.hive.jdbc.HiveDriver";

    private static Connection connection = null;
    private static Statement statement = null;
    private static ResultSet resultSet = null;

    // 查询tables sql
    private static String showTableSql = "show tables";

    // 创建内部表statistics sql
    private static String createSql = "create table statistics(ip string,domain_name string,datatime string,target string,status int)row format delimited fields terminated by '#' ";
    // 加载数据到statistics sql
    private static String localDataSql = "load data local inpath '/opt/soft/hadoop-2.6.0-cdh5.7.0/dnsSample' into table statistics ";

    // 统计出statistics表中各域名个数
    private static String countSql = "select domain_name,count(*) from statistics group by domain_name";




    public static void main(String[] args) throws SQLException {

        //  加载hive驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载失败");
            e.printStackTrace();
        }

        try {
            // 连接hive
            connection = DriverManager.getConnection(url, userName, passwd);
            if (connection != null) {
                System.out.println("hive 连接成功");
            } else {
                System.out.println("hive 连接失败");
            }

            statement = connection.createStatement();

            // 获取数据库中所有的表
            resultSet = statement.executeQuery(showTableSql);
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1));
            }

            statement.execute(createSql);
            statement.execute(localDataSql);
            resultSet = statement.executeQuery(countSql);
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2));
            }





        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
            if(connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        }
    }
}
